package com.gis3c.sys.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by hukekuan on 2018/1/29.
 */
@Component("exceptionHandler")
public class C3ExceptionHandler implements HandlerExceptionResolver {
    private static final Logger logger = Logger.getLogger(C3ExceptionHandler.class);
    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response, Object handler, Exception ex) {
        logger.error(ex.getMessage(),ex);

        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

        Map<String, Object> model = new HashMap<String, Object>();
        model.put("error", ex.getMessage());
        String header = request.getHeader("X-Requested-With");
        if(header != null && !"".equals(header)
                && (header.equals("X-Requested-With") || header.equals("XMLHttpRequest"))){
            response.setContentType("application/json;charset=UTF-8");
            ObjectMapper mapper = new ObjectMapper();
            try(PrintWriter pw = response.getWriter()){
                pw.write(mapper.writeValueAsString(model));
                pw.flush();
            }catch(IOException e){
                e.printStackTrace();
            }
            return null;
        }

        return new ModelAndView("sys/error",model);
    }
}
